/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.solr.manager;

import com.lvyh.lightframe.solr.anotation.SolrField;
import com.lvyh.lightframe.solr.common.SolrPageParam;
import com.lvyh.lightframe.solr.common.SolrPageResult;
import com.lvyh.lightframe.solr.common.SolrQueryCondition;
import com.lvyh.lightframe.solr.exception.SolrIndexException;
import com.lvyh.lightframe.solr.util.ReflectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Solr client management class
 *
 * @author lvyh 2021/03/07.
 */
public class SolrClientManager<T> {
    private final static Logger logger = LoggerFactory.getLogger(SolrClientManager.class);
    // Sort type
    public static final String DESC = "desc";
    public static final String ASC = "asc";

    private HttpSolrClient solrClient = null;

    public SolrClientManager(String url) {
        if (solrClient == null) {
            HttpSolrClient.Builder builder = new HttpSolrClient.Builder(url);
            solrClient = builder.withConnectionTimeout(10000).withSocketTimeout(60000).build();
        }
    }

    public SolrClientManager(SolrClient solrClient) {
        this.solrClient = (HttpSolrClient) solrClient;
    }

    public HttpSolrClient getSolrClient() {
        return solrClient;
    }

    public void setSolrClient(HttpSolrClient solrClient) {
        this.solrClient = solrClient;
    }

    /**
     * New index (new and modified)
     */
    public void createIndex(T entity) {
        Field[] fields = ReflectionUtils.getAllFields(entity.getClass());

        SolrInputDocument doc = new SolrInputDocument();
        for (Field field : fields) {
            doc.addField(field.getName(), ReflectionUtils.invokeGetterMethod(entity, field.getName()));
        }

        try {
            solrClient.add(doc);
            solrClient.commit();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new SolrIndexException(e.getMessage());
        }
    }

    /**
     * Batch adding index
     */
    public void createIndex(List<T> list) {
        if (list == null || list.size() <= 0) {
            return;
        }
        for (T entity : list) {
            this.createIndex(entity);
        }
    }

    /**
     * Batch adding index
     */
    public void batchAddIndex(List<T> list) throws Exception {
        if (list == null || list.size() <= 0) {
            return;
        }

        Collection<SolrInputDocument> docs = new ArrayList<>();
        for (T entity : list) {
            SolrInputDocument doc = new SolrInputDocument();
            Field[] fields = ReflectionUtils.getAllFields(entity.getClass());
            for (Field field : fields) {
                doc.addField(field.getName(), ReflectionUtils.invokeGetterMethod(entity, field.getName()));
            }
            docs.add(doc);
        }

        solrClient.add(docs);
        solrClient.commit();
    }

    /**
     * Batch delete the specified index according to ID
     */
    public int deleteIndex(List<String> ids) {
        int status = 0;
        if (ids == null || ids.size() <= 0) {
            return status;
        }
        try {
            UpdateResponse response = solrClient.deleteById(ids);
            status = response.getStatus();
            solrClient.commit();
        } catch (SolrServerException | IOException e) {
            logger.error(e.getMessage(), e);
            throw new SolrIndexException(e.getMessage());
        }
        return status;
    }

    /**
     * Batch deletion of associated indexes according to query
     */
    public int deleteIndex(String query) {
        int status = 0;
        if (StringUtils.isEmpty(query)) {
            return status;
        }
        try {
            UpdateResponse response = solrClient.deleteByQuery(query);
            status = response.getStatus();
            solrClient.commit();
        } catch (SolrServerException | IOException e) {
            logger.error(e.getMessage(), e);
            throw new SolrIndexException(e.getMessage());
        }
        return status;
    }

    /**
     * Solr search query
     */
    public List<T> search(SolrQueryCondition<T> condition, Class<?> entity, Map<String, SolrQuery.ORDER> sortMap, SolrPageParam pageParam) throws Exception {
        List<T> container = new ArrayList<T>();

        SolrQuery solrQuery = new SolrQuery();

        // Set query criteria
        String commonQueryCondition = buildSolrQueryCondition(condition);
        if (commonQueryCondition.length() > 0) {
            if (Objects.equals(condition.getConditionType(), "OR")) {
                commonQueryCondition = commonQueryCondition.substring(" OR ".length(), commonQueryCondition.length());
            } else {
                commonQueryCondition = commonQueryCondition.substring(" AND ".length(), commonQueryCondition.length());
            }
            solrQuery.setQuery(commonQueryCondition);// Query by condition
        } else {
            solrQuery.setQuery("*:*");// No parameter
        }

        // Set query properties
        StringBuilder builder = new StringBuilder();
        Field[] fields = ReflectionUtils.getAllFields(entity);
        for (Field field : fields) {
            builder.append(field.getName()).append(",");
        }
        String field = builder.toString();
        field = field.substring(0, field.length() - 1);
        solrQuery.setFields(field);//Results show all columns

        // Set sort
        if (sortMap != null) {
            for (String key : sortMap.keySet()) {
                SolrQuery.ORDER value = sortMap.get(key);
                if (StringUtils.isNotBlank(key) && value != null) {
                    solrQuery.setSort(key, value);
                }
            }
        }

        // paging
        int start = (pageParam.getPageNo() - 1) * pageParam.getPageSize();
        int size = pageParam.getPageSize();

        // Specifies the initial offset to the result set. Can be used to paginate the results. The default value is 0
        solrQuery.set("start", start);
        // Returns the maximum number of documents. The default value is 10.
        solrQuery.set("rows", size);

        QueryResponse response = solrClient.query(solrQuery);
        SolrDocumentList docs = response.getResults();
        if (null == docs || docs.size() == 0) {
            return null;
        }
        for (SolrDocument doc : docs) {
            T obj = (T) entity.newInstance();
            ArrayList<Field> searchFields = new ArrayList<Field>(Arrays.asList(ReflectionUtils.getAllFields(obj.getClass())));
            for (Field searchField : searchFields) {
                Class<?> propertyClass = searchField.getType();
                String propertyName = searchField.getName();

                if (propertyClass.equals(Double.class)) {
                    Double value = Double.class.cast(doc.getFieldValue(propertyName));
                    ReflectionUtils.invokeSetterMethod(obj, propertyName, value);

                } else if (propertyClass.equals(Float.class)) {
                    Float value = Float.class.cast(doc.getFieldValue(propertyName));
                    ReflectionUtils.invokeSetterMethod(obj, propertyName, value);

                } else if (propertyClass.equals(Integer.class)) {
                    Integer value = Integer.class.cast(doc.getFieldValue(propertyName));
                    ReflectionUtils.invokeSetterMethod(obj, propertyName, value);

                } else if (propertyClass.equals(Long.class)) {
                    Long value = Long.class.cast(doc.getFieldValue(propertyName));
                    ReflectionUtils.invokeSetterMethod(obj, propertyName, value);

                } else {
                    String value = (String) doc.getFieldValue(propertyName);
                    if (!StringUtils.isEmpty(value)) {
                        ReflectionUtils.invokeSetterMethod(obj, propertyName, value);
                    }
                }
            }
            container.add(obj);
        }
        return container;
    }


    public String buildSolrQueryCondition(SolrQueryCondition<T> condition) {
        Object obj = condition.getData();
        Field[] fields = obj.getClass().getDeclaredFields();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            try {
                //Set the field to be visible, otherwise the private property cannot be obtained
                field.setAccessible(true);
                Object object = field.get(obj);

                // Only get non empty fields and configure Solr annotation fields
                SolrField solrField = field.getAnnotation(SolrField.class);
                if (object != null && StringUtils.isNotBlank(object.toString()) && solrField != null) {
                    if (Objects.equals(condition.getConditionType(), "OR")) {
                        stringBuilder.append(" OR ");// OR
                    } else {
                        stringBuilder.append(" AND ");// AND
                    }
                    stringBuilder.append(field.getName());
                    stringBuilder.append(":");
                    if (solrField.isFuzzySearch()) {
                        stringBuilder.append("*" + parseKeywords(field.get(obj).toString()) + "*");
                    } else {
                        stringBuilder.append(parseKeywords(field.get(obj).toString()));
                    }
                }
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return stringBuilder.toString();
    }

    /**
     * Solr paging retrieval
     */
    public SolrPageResult<T> searchPage(SolrQueryCondition<T> condition, Class<?> entity, Map<String, SolrQuery.ORDER> sortMap, SolrPageParam pageParam) throws Exception {
        List<T> container = new ArrayList<T>();
        SolrQuery solrQuery = new SolrQuery();

        // 设置查询条件
        String commonQueryCondition = buildSolrQueryCondition(condition);
        if (commonQueryCondition.length() > 0) {
            if (Objects.equals(condition.getConditionType(), "OR")) {
                commonQueryCondition = commonQueryCondition.substring(" OR ".length(), commonQueryCondition.length());
            } else {
                commonQueryCondition = commonQueryCondition.substring(" AND ".length(), commonQueryCondition.length());
            }
            solrQuery.setQuery(commonQueryCondition);
        } else {
            solrQuery.setQuery("*:*");
        }

        StringBuilder builder = new StringBuilder();
        Field[] fields = ReflectionUtils.getAllFields(entity);
        for (Field field : fields) {
            builder.append(field.getName()).append(",");
        }
        String field = builder.toString();
        field = field.substring(0, field.length() - 1);
        solrQuery.setFields(field);
        if (sortMap != null) {
            for (String key : sortMap.keySet()) {
                SolrQuery.ORDER value = sortMap.get(key);
                if (StringUtils.isNotBlank(key) && value != null) {
                    solrQuery.setSort(key, value);
                }
            }
        }

        int start = (pageParam.getPageNo() - 1) * pageParam.getPageSize();
        int size = pageParam.getPageSize();

        solrQuery.set("start", start);
        solrQuery.set("rows", size);

        QueryResponse response = solrClient.query(solrQuery);
        SolrDocumentList docs = response.getResults();
        if (null == docs || docs.size() == 0) {
            return null;
        }
        for (SolrDocument doc : docs) {
            T obj = (T) entity.newInstance();
            ArrayList<Field> searchFields = new ArrayList<Field>(Arrays.asList(ReflectionUtils.getAllFields(obj.getClass())));
            for (Field searchField : searchFields) {
                Class<?> propertyClass = searchField.getType();
                String propertyName = searchField.getName();
                if (propertyClass.equals(Double.class)) {
                    Double value = Double.class.cast(doc.getFieldValue(propertyName));
                    ReflectionUtils.invokeSetterMethod(obj, propertyName, value);

                } else if (propertyClass.equals(Float.class)) {
                    Float value = Float.class.cast(doc.getFieldValue(propertyName));
                    ReflectionUtils.invokeSetterMethod(obj, propertyName, value);

                } else if (propertyClass.equals(Integer.class)) {
                    Integer value = Integer.class.cast(doc.getFieldValue(propertyName));
                    ReflectionUtils.invokeSetterMethod(obj, propertyName, value);

                } else if (propertyClass.equals(Long.class)) {
                    Long value = Long.class.cast(doc.getFieldValue(propertyName));
                    ReflectionUtils.invokeSetterMethod(obj, propertyName, value);

                } else {
                    String value = (String) doc.getFieldValue(propertyName);
                    if (!StringUtils.isEmpty(value)) {
                        ReflectionUtils.invokeSetterMethod(obj, propertyName, value);
                    }
                }
            }
            container.add(obj);
        }
        return new SolrPageResult(pageParam.getPageSize(), (int) docs.getNumFound(), container);
    }


    /**
     * Escape user input query illegal string
     */
    protected static String parseKeywords(String s) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            // These characters are part of the query syntax and must be escaped
            if (c == '\\' || c == '+' || c == '-' || c == '!' || c == ':' || c == '^' || c == '[' || c == ']' || c == '\"'
                    || c == '{' || c == '}' || c == '~' || c == '*' || c == '?' || c == '|' || c == '&' || c == ';' || c == '/'
                    ) {
                sb.append('\\');
            }

            sb.append(c);
        }
        return sb.toString();
    }
}
